<?php
include 'inner/init.php';
protect_reg();
include 'includes/overall/header.php';

if (empty($_POST) === false) {
    $required_fields = array('username', 'password', 'password2', 'fname', 'lname', 'email');
    foreach($_POST as $key=>$value){
        if (empty($value) && in_array($key, $required_fields) === true){
            $error[] = 'Fields marked with an asterisk must be filled!';
            break 1;
        }
    }
    
    if (empty($error) === true){
        if (user_exists($_POST['username']) === true) {
            $error[] = 'Oops! the username \'' . $_POST['username'] . '\' is already taken.';
        }
        if (preg_match("/\\s/", $_POST['username']) == true){
            $error[] = 'Username must not contain any spaces.';
        }
        
        if (strlen($_POST['password']) < 6){
            $error[] = 'Password must be at least 6 characters';
        }
        if ($_POST['password'] !== $_POST['password2']) {
            $error[] = 'Passwords do not match';
        }
        if (email_exists($_POST['email'])=== true){
            $error[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already in use.';   
        }
    } 
}



?>
            
 <h1>Registration Completed</h1>
 <?php
 
 if (isset($_GET['success']) && empty($_GET['success'])) {
    echo 'You\'ve been registered successfully! <br>You may now log in using your account. :)';
 } else{
 
 if (empty($_POST) === false && empty($error) === true){
    $register_data = array(
        'username' => $_POST['username'],
        'password' => $_POST['password'],
        'fname'    => $_POST['fname'],
        'lname'    => $_POST['lname'],
        'email'    => $_POST['email']
    );
    
    register_user($register_data);
    header('Location: reg.php?success');
    exit();
    
 } else if(empty($error) === false){
    echo output_error($error);
 }

 ?>
 
<form action="" method="post">
    <ul>

        <li>
            Username*:<br>
            <input type="text" name="username">
        </li>
        <li>
            Password*<br>
            <input type="password" name="password">
        </li>
        <li>
            Re-enter Password*:<br>
            <input type="password" name="password2">
        </li>
        <li>
            Your First name*:<br>
            <input type="text" name="fname">
        </li>
        <li>
            Your Last name*:<br>
            <input type="text" name="lname">
        </li>
        <li>
            Email*:<br>
            <input type="text" name="email">
        </li>
        <li>
            <input type="submit" value="Register">
        </li>
    </ul>
     
</form>


<?php
 }
 
include 'includes/overall/footer.php'; ?>  